package com.chaoxing.user.service.impl;

import com.chaoxing.user.beans.DO.AreaInfo;
import com.chaoxing.user.beans.DTO.AreaInfoDTO;
import com.chaoxing.user.beans.DTO.AreaTreeDTO;
import com.chaoxing.user.beans.DTO.Result;
import com.chaoxing.user.convert.AreaInfoConvert;
import com.chaoxing.user.dao.IAreaDao;
import com.chaoxing.user.service.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author dingyuanyuan
 */
@Service
public class AreaServiceImpl implements IAreaService {

    @Autowired
    private IAreaDao areaDao ;

    @Override
    public Result selectAreaListById(String id) {

        if (null == id || "".equals(id.trim())){
            id = "0" ;
        }

        List<AreaInfo> areaInfos =  areaDao.selectAreaListById(id) ;

        if (null != areaInfos && areaInfos.size()>0){
            List<AreaInfoDTO> areaInfoDTOList=  AreaInfoConvert.INSTANCE.doList2DtoList(areaInfos) ;
            return  Result.success(areaInfoDTOList,"查询成功") ;
        }

        return Result.fail("数据为空，查询失败");
    }

    @Override
    public Result selectAreaDataById(String id) {

        if (null == id || "".equals(id.trim())){
            id = "0" ;

        }
        AreaInfo areaInfo ;
        if ("0".equals(id)){
            areaInfo =   areaDao.selectAreaInfoById("1") ;
        }else {
            areaInfo =   areaDao.selectAreaInfoById(id) ;
        }

        if (null==areaInfo){
            return Result.fail("数据为空，查询失败");
        }

        AreaTreeDTO  areaTreeDTO = new AreaTreeDTO() ;
        areaTreeDTO.setAreaInfoDTO(AreaInfoConvert.INSTANCE.do2Dto(areaInfo));

        List<AreaInfo> areaInfos =  areaDao.selectAreaListById(id) ;

        if (null != areaInfos && areaInfos.size()>0){
            List<AreaTreeDTO> areaDataDTOS = getAraaList(areaInfos) ;
            areaTreeDTO.setAreaTreeDTOS(areaDataDTOS);

            return  Result.success(areaDataDTOS,"查询成功") ;
        }

        return Result.fail("数据为空，查询失败");


    }


    /**
     * 无限极递归
     *
     *
     * @param list
     * @return
     */
    private  List<AreaTreeDTO> getAraaList(List<AreaInfo> list) {
        List<AreaTreeDTO> areaDataDTOS = new ArrayList<>() ;
//1，第一层
        list.stream().forEach(areaInfo -> {
            Long parentId = areaInfo.getId();
//2，第二层
            List<AreaInfo> areaInfos = areaDao.selectAreaListById(parentId.toString());

            AreaTreeDTO areaTreeDTO = new AreaTreeDTO() ;
            areaTreeDTO.setAreaInfoDTO(AreaInfoConvert.INSTANCE.do2Dto(areaInfo));

            if (null!=areaInfos && areaInfos.size()>0){
                //            递归核心地方
                List<AreaTreeDTO> areaTreeDTOList =   getAraaList(areaInfos) ;
                areaTreeDTO.setAreaTreeDTOS(areaTreeDTOList);
            }
            areaDataDTOS.add(areaTreeDTO) ;

        });

        return areaDataDTOS ;
    }



}
